<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="出库单编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入出库单编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="出库仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repositoryName">
              <j-popup
                v-model="model.repositoryName"
                field="repositoryName"
                org-fields="name,code"
                dest-fields="repositoryName,repositoryCode"
                code="select_repository"
                :multi="false"
                @input="popupCallback"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="出库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="outTime">
              <j-date
                placeholder="请选择出库日期"
                v-model="model.outTime"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="出库人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="outPeople">
              <j-select-user-by-dep v-model="model.outPeople" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="领取人姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="personnel">
              <j-select-user-by-dep v-model="model.personnel" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="领取人所在公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="company">
              <j-select-depart v-model="model.company" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="领取人所在部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dapartment">
              <j-select-depart v-model="model.dapartment" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment">
              <j-upload v-model="model.attachment" :number="10" :before-upload="beforeUpload"></j-upload>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="出库总金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="total">
              <a-input-number v-model="model.total" placeholder="请输入出库总金额" style="width: 100%" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="出库物品" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="purchaseStockOutGoodsTable.loading"
          :columns="purchaseStockOutGoodsTable.columns"
          :dataSource="purchaseStockOutGoodsTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          @valueChange="valueChange"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
import { stockOutCodeRule } from '@/api/api'
import currency from 'currency.js'

export default {
  name: 'PurchaseStockOutForm',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        code: '',
      },
      validatorRules: {
          repositoryName: [
              { required: true, message: '请选择出库仓库'},
            ],
          outTime: [
            { required: true, message: '请选择出库日期'},
          ],
          outPeople: [
            { required: true, message: '请选择出库人'},
          ],
          personnel: [
            { required: true, message: '请选择领取人姓名'},
          ],
          company: [
            { required: true, message: '请选择领取人所在公司'},
          ],
          dapartment: [
            { required: true, message: '请选择领取人所在部门'},
          ],
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      refKeys: ['purchaseStockOutGoods'],
      tableKeys: ['purchaseStockOutGoods'],
      activeKey: 'purchaseStockOutGoods',
      // 出库物品
      purchaseStockOutGoodsTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物品名称',
            key: 'goodsName',
            type: FormTypes.popup,
            popupCode: 'stock_select',
            destFields: 'goodsName,goodsTypeCode,goodsCode,size,unit,unitPrice,brand,finalNumber',
            orgFields:
              'goods_name,goods_type_code,goods_code,goods_size,goods_unit,goods_unit_price,brand,total_number',
            param: {},
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '请输入${title}'},],
          },
          {
            title: '物品分类',
            key: 'goodsTypeCode',
            type: FormTypes.select,
            dictCode: 'purchase_goods_type',
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '物品编码',
            key: 'goodsCode',
            type: FormTypes.input,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '品牌',
            key: 'brand',
            type: FormTypes.input,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '规格/尺寸/型号',
            key: 'size',
            type: FormTypes.input,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '单位',
            key: 'unit',
            type: FormTypes.select,
            dictCode: 'purchase_unit',
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '单价',
            key: 'unitPrice',
            type: FormTypes.input,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [
              {pattern: /^\d+(\.{0,1}\d+){0,1}$/, message: '${title}必须非负数'}
            ],
          },
          {
            title: '库存数量',
            key: 'finalNumber',
            type: FormTypes.inputNumber,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '出库数量',
            key: 'number',
            type: FormTypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [
              {
                handler(type, value, row, column, callback, target) {
                  let { values } = target.getValuesSync({ validate: false, rowIds: [row.id] })
                  const num = Number(values[0].number)
                  if (!num){
                    callback(false, `出库数量不能为空`)
                  }
                  const finalnum = Number(values[0].finalNumber)
                  if (value > finalnum) {
                    callback(false, `出库数量不能大于库存数量`)
                  } else {
                    callback(true)
                  }
                },
                message: '${title}默认提示',
              },
            ],
          },
          {
            title: '小计',
            key: 'total',
            type: FormTypes.inputNumber,
            disabled: true,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },

          {
            title: 'goods_name',
            key: 'goods_name',
            type: 'hidden',
          },

          {
            title: 'goods_type_code',
            key: 'goods_type_code',
            type: 'hidden',
          },

          {
            title: 'goods_code',
            key: 'goods_code',
            type: 'hidden',
          },

          {
            title: 'unit_price',
            key: 'unit_price',
            type: 'hidden',
          },

          {
            title: 'final_number',
            key: 'final_number',
            type: 'hidden',
          },
        ],
      },
      url: {
        add: '/purchase/purchaseStockOut/add',
        edit: '/purchase/purchaseStockOut/edit',
        purchaseStockOutGoods: {
          list: '/purchase/purchaseStockOut/queryPurchaseStockOutGoodsByMainId',
        },
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {},
  methods: {
    valueChange(obj) {
      // console.log(obj)
      if (obj.row.unitPrice >= 0 && obj.row.number >= 0) {
        // let sub_total = obj.row.unitPrice * obj.row.number
        let sub_total = currency(obj.row.unitPrice).multiply(obj.row.number)
        if (sub_total != obj.row.total) {
          obj.target.setValues([
            {
              rowKey: obj.row.id,
              values: {
                total: sub_total,
              },
            },
          ])
        }
      }
      obj.target.getValues((error, values) => {
        let total = 0
        values.map((item) => {
          // total += item.total
          total = currency(total).add(item.total)
        })
        console.log(total)
        this.model.total = total.value
      })
    },
    //初始化出库编码
    init() {
      stockOutCodeRule({}).then((res) => {
        if (res.success) {
          this.model.code = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    addBefore() {
      this.purchaseStockOutGoodsTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.purchaseStockOutGoods.list, params, this.purchaseStockOutGoodsTable)
      }
      if (!this.model.id) {
        this.init()
      }
      this.purchaseStockOutGoodsTable.columns[0].param = {
        repositoryCode: this.model.repositoryCode,
        repositoryName: this.model.repositoryName
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)

      return {
        ...main, // 展开
        purchaseStockOutGoodsList: allValues.tablesValue[0].values,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    close() {
      this.visible = false
      this.$emit('close')
      this.$refs.form.clearValidate()
    },
    popupCallback(value, row) {
      this.model = Object.assign(this.model, row)
      this.purchaseStockOutGoodsTable.columns[0].param = row
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('文件过大');
      }
      const isMax = this.model.attachment && this.model.attachment.split(',').length >= 10
      if(isMax){
        this.$message.error('最多上传文件数10个');
      }
      return isLt2M && !isMax;
    },
  },
}
</script>

<style scoped>
</style>